<!--策略启动-多币对-->
<template>
  <div class="all" @viewappear="viewappear" @viewdisappear="viewdisappear">
    
    <scroller class="scroller">
      <div class="wrapper" v-if="isShow">

        <!--服务器-->
        <VServer class="server" ref="server" 
        :isPrivate="true"></VServer>

        <!--API-->
        <VApi class="api" ref="api" :copyPair="copyPair" :noExchanged="noExchanged" v-model="api" @apiChange="apiChange"></VApi>
        
        <div v-if="pairMap">
          <!--交易对-->
          <VPair class="pair" ref="pair" :pairMap="pairMap" @pairClick="pairClick"></VPair>

          <!--多币对-->
          <VPair class="pair" ref="pairs" v-for="(item, index) in pairMaps" v-bind:key="index"
          :pairMap="item" :arrow="false" @closeClick="closePairClick(index)"></VPair>
          <div class="acenter">
            <div class="pair-but1 main-b1"  @click="addPairClick">
              <div class="pair-but2 bg3">
                <div class="pair-but3 main1">
                  <text class="font28 text1">{{T('添加')+'  +'}}</text>
                </div>
              </div>
            </div>
          </div>

          <!--投资方向 2021.6.1隐藏多币对投资方向，因为投资交易币，策略持仓显示逻辑错误-->
          <!-- <VTarget class="target" v-if="isTarget" :target="target" :counterCoin="pairMap.counterCoin" 
          :baseCoin="pairMap.baseCoin" @click="targetClick"></VTarget> -->

          <!--参数列表-->
          <VParam class="param" ref="param" v-model="reserveOpen" 
          :isMany="true" :reserves="reserves" :investCoin="investCoin" 
          :pairMap="pairMap" :isRestore="!copyPair" :isModify="!!copyPair"
          @paramChange="paramChange"></VParam>

          <!--投入资金-->
          <div class="line bg3" v-if="reserveOpen"></div>
          <VInputUp class="input" v-if="reserveOpen" ref="input" v-model="investCoinnNum"
          :type="'many'" :name="strategyName" :api="api" :investCoin="investCoin" 
          :params="params" :pairMap="pairMap" :pairNum="pairMaps.length + 1 + ''" :limitMap="limitMap"></VInputUp>

          <!--其他设置-->
          <VSet class="set" ref="set" v-model="sets" @open="setOpen"></VSet>

          <!--跟单设置-->
          <div v-if="sets && sets.isOpen && (followMimic || api.apiId.length)">
            <div class="line bg3"></div>
            <VFollow class="follow" ref="follow" v-model="follows" 
            :type="'many'" :name="strategyName" :params="params" :investCoin="investCoin" :investNum="investCoinnNum" 
            :pairMap="pairMap" :commissionMap="commissionMap" :pairMaps="pairMaps" @follow="setOpen"></VFollow>
          </div>
        </div>
      </div>
    </scroller>

    <!--启动-->
    <div class="up bg3">
      <div class="up-but main1" @click="upClick">
        <text class="font32 text1">{{T('启动')}}</text>
      </div>
    </div>
  </div>
</template>

<script>

//组件
import VServer from "@/up/view/VServer.vue";
import VApi from "@/up/view/VApi.vue";
import VPair from "@/up/view/VPair.vue";
import VTarget from "@/up/view/VTarget.vue";
import VParam from "@/up/view/VParam.vue";
import VInputUp from "@/up/view/VInputUp.vue";
import VSet from "@/up/view/VSet.vue";
import VFollow from "@/up/view/VFollow.vue";

//功能
import modal from "@/_js/modal";
import math from "@/_js/math";
import navigator from "@/_js/navigator"; 
import broadcast from "@/_js/broadcast";
import mUp from "@/up/amUp";
import amCopy from './amCopy'


import weexHttp from "@/_js/https";
const weexFunction = weex.requireModule('WeexFunction');
const dom = weex.requireModule('dom')

import I18N from "@/_i18n/i18n";
var T = I18N.t;

export default {

  components: {
    VServer,
    VApi,
    VPair,
    VTarget,
    VParam,
    VInputUp,
    VSet,
    VFollow,
  },

  props:{

    isTarget:{ //turn显示投资方向
      type:Boolean,
      default:true,
    },
    targetx:{ //turn赚交易币 false赚本币
      type:Boolean,
      default:false,
    },

    strategyId:String, //策略ID
    strategyName:String, //策略名称
    noExchanged:{ //不可选交易所对象{name}
      type:Object,
      default:{'uniswap':'Uniswap只支持马丁追踪自定义启动'},
    }, 

    copyConfig:Object, //复制配置
  },
  
  data() {
    return {
      T:T,
      math:math,
      isUp:false, //turn已经启动过合约

      limitMap:undefined, // 投入限制
      api:undefined, //当前选中API
      pairMap:undefined, //当前选中交易对
      pairMaps:[], //多币对
      manyMimic:false, //turn支持模拟盘多币对

      target:this.targetx, //turn赚交易币 false赚本币
      investCoin:undefined, //投资币
      investCoinnNum:'', //投资数量

      reserveOpen:undefined, //turn 参数展开
      reserves:undefined, //参数数组
      params:undefined, //参数数组（投入限制联动使用）

      sets:undefined, //其他设置
      follows:undefined, //跟单设置
      followMimic:false, //false 模拟盘开放跟单

      configMap:undefined, //执行配置
      commissionMap:undefined, //跟单佣金

      /** 特殊代码：隐藏特定参数
       * PRICE_MAX 价格上限
       * PRICE_MIN 价格下限
       */
      visiables:{'PRICE_MAX':'1', 'PRICE_MIN':'1'},


      //复制配置
      copyPair: undefined, //交易对
      copyReserves: undefined, //参数数组
      copySets: undefined, //其他设置
      isShow:false,
    };
  },

  mounted() {
    var data = amCopy.getCopyData(this.copyConfig);
    if (data) {
      this.copyPair = data.copyPair;
      this.target = this.copyPair.investCoin == this.copyPair.counterCoin;
      this.copyReserves = data.copyReserves;
      this.copySets = data.copySets;
    }

    this.isShow = true;
  },

  methods: {

    //初始化数据
    initData(counterCoin, baseCoin) {
      this.pairMaps = [];  //多币对
      this.reserveOpen = true; //参数展开
      this.investCoin = this.target ? counterCoin : baseCoin;  //投资币

      //其他设置
      if (this.copySets) {
        this.sets = this.copySets;
      } else {
        this.sets = this.sets ? {} : undefined; 
      }
    },

    /*************************************************通信触发*/
    //完全显示
    viewappear() {
      this.$refs.pair && this.$refs.pair.viewappear();

      if (this.$refs.pairs) {
        for (let index = 0; index < this.$refs.pairs.length; index++) {
          var ref = this.$refs.pairs[index];
          ref.viewappear();
        }
      }
    },

    //完全隐藏
    viewdisappear() {
      this.$refs.pair && this.$refs.pair.viewdisappear();

      if (this.$refs.pairs) {
        for (let index = 0; index < this.$refs.pairs.length; index++) {
          var ref = this.$refs.pairs[index];
          ref.viewdisappear();
        }
      }
    },

    /********************************************** https*/
    //http策略-自定义
    httpStrategyAi(target, counterCoin, baseCoin){

      modal.showLoad();
      var param = {'strategyId':this.strategyId, 
                   'exchangeId':this.api.exchangeId, 
                   'exchangeName':this.api.exchangeName, 
                   'counterCoin':counterCoin, 
                   'baseCoin':baseCoin,
                   'investType':target};
      weexHttp.post("strategyV3/manyPairStartPage",param,true,(data)=>{
        modal.hideLoad();
        if(data.status == 200){
          data = data.data;
          var pairMap = data.pairMap;
          pairMap['baseCoinUsdPrice'] =  math.chu(pairMap.usdPrice, pairMap.last, math.getNumber(pairMap.baseCoinDecimal));

          this.configMap = data.configMap; //执行配置
          this.target = target; //策略方向
          this.manyMimic = data.manyMimic; //模拟盘开发加币对
          this.followMimic = data.followMimic; //模拟盘开放跟单
          this.commissionMap = data.commissionMap;

          //交易对改变：保存API默认配置
          if (counterCoin != pairMap.counterCoin || baseCoin != pairMap.baseCoin) {
            counterCoin = pairMap.counterCoin;
            baseCoin = pairMap.baseCoin;
          }
          this.$refs.api.setDefaultApi(this.api.apiId, counterCoin, baseCoin);

          //特殊代码：隐藏特定参数
          var reserves =  this.configMap.reserves;
          for (let index = 0; index < reserves.length; index++) {
            var reserve = reserves[index];
            if (this.visiables[reserve.target]) {
              reserve.visiable = '0';
            }
          }
          this.limitMap =  data.limitMap; //投入限制
          this.reserves = this.copyReserves ? this.copyReserves : reserves; //参数数组
          this.params = reserves; //参数数组（投入限制联动使用）
          
          this.initData(counterCoin, baseCoin); //初始化数据
          this.pairMap = pairMap; //交易对
          this.httpCheckContract();
        } else {
          modal.toast(data.msg);
        }
      });
    },


    //http策略-启动过合约策略
    httpCheckContract(){
      if (this.api.apiId == '') {
        this.isUp = false;
        return;
      }

      var param = {'apiId':this.api.apiId,  
                   'exchangeName':this.api.exchangeName};
      weexHttp.post("contract/querySpotPermission",param,true,(data)=>{
        if(data.status == 200){
          var data = data.data;
          this.isUp = data.isStartStrategy;
          if (this.isUp) {
            this.tipeUpCoin();
          }
        } else {            
          this.isUp = false;
        }
      });
    },

    /********************************** 其他*/
    //提示启动过该币种
    tipeUpCoin(){
      var tipe = T('单个统一账户只支持一个合约策略且执行合约策略时不可执行币币策略，&{1}账户已有执行中的合约策略，您可前往执行列表查看。');
      tipe = tipe.replace("&{1}", this.api.apiName);
      modal.alert(tipe,()=>{
      });
    },

    /********************************** 改变*/
    //API改变
    apiChange(counterCoin, baseCoin){

      counterCoin = counterCoin ? counterCoin : this.pairMap.counterCoin;
      baseCoin = baseCoin ? baseCoin : this.pairMap.baseCoin;
      this.httpStrategyAi(this.target, counterCoin, baseCoin);
    },

    //参数改变
    paramChange(){
      this.params = this.$refs.param.getParam();
    },

    /********************************** 点击*/
    //交易对
    pairClick() {
      
      var param = {exchangeId:this.api.exchangeId,
                  exchangeName:this.api.exchangeName,
                  counterCoin:this.pairMap.counterCoin,
                  baseCoin:this.pairMap.baseCoin};
      navigator.open('', 'up/SelectPairNorm', param);

      var self = this;
      broadcast.subscribeOnce('SelectPairNorm', (pair)=>{
        
        if (pair.counterCoin == self.pairMap.counterCoin && 
            pair.baseCoin == self.pairMap.baseCoin) {
          return;
        }
        self.httpStrategyAi(self.target, pair.counterCoin, pair.baseCoin);
      });
    },
    
    //关闭币对
    closePairClick(index) {
      this.pairMaps.splice(index,1);
    },

    //添加币对
    addPairClick(){

      if (this.api.apiId == '' && !this.manyMimic){
        modal.alert('添加多币对请使用实盘API');
        return;
      }

      var param = {'exchangeName':this.api.exchangeName,
                  'exchangeId':this.api.exchangeId,
                  'pairMaps':this.pairMaps,
                  'target':this.target,
                  'counterCoin':this.pairMap.counterCoin,
                  'baseCoin':this.pairMap.baseCoin};
      navigator.open('', 'up/SelectPairMany', param);
      
      broadcast.subscribeOnce("SelectPairMany", (data)=>{
        this.pairMaps = data;
      });
    },

    //策略方向
    targetClick(target) {
      this.httpStrategyAi(target, this.pairMap.counterCoin, this.pairMap.baseCoin);
    },

    //其他设置-展开
    setOpen() {
      setTimeout(() => {
        if (this.$refs.follow) {
          dom.scrollToElement(this.$refs.follow, {offset:0});
        } else if (this.$refs.set) {
          dom.scrollToElement(this.$refs.set, {offset:0});
        }
      }, 100);
    },

    //启动
    upClick() {
      
      //启动过OkexV5合约
      if (this.isUp) {
        this.tipeUpCoin();
        return;
      }

       //服务器检查
      if (this.$refs.server && this.$refs.server.checkError()) {
        return;
      }
      
      //参数检测
      if (this.$refs.param.checkError()) {
        return;
      }

      //投入资金-测试
      if (this.$refs.input.checkError()) {
        return;
      }

      //其他设置
      if (this.$refs.set.checkError()) {
        return;
      }
      
      modal.showLoad();

      var executeConfig = JSON.parse(JSON.stringify(this.configMap));
      var reserves =  this.$refs.param.getParam(); 
      var setMap = this.$refs.set.getParam(); 
      var isOpenFollow = this.followMimic || this.api.apiId  != '';
      isOpenFollow = this.follows ? this.follows.isFollow : isOpenFollow;
      var followMap = this.follows ? this.follows.followMap : undefined;

      
      var address = '';
      if (this.$refs.server) {
        var server =  this.$refs.server.server;
        address = server ? server.innerIp : '';
      }

      var tradeFee = isNaN(this.api.tradeFee) ? '0' : this.api.tradeFee;
      var param = {'address':address,
                  'api':this.api, 'buyFee':tradeFee,
                  'strategyId':this.strategyId,
                  'investCoin':this.investCoin, 'investCoinnNum':this.investCoinnNum,
                  'investType':this.target, 'startType':'OFFICIAL',
                  'executeConfig':executeConfig, 'pairMap':this.pairMap, 'pairs':this.pairMaps,
                  'reserves':reserves, 'setMap':setMap, 
                  'isOpenFollow':isOpenFollow};
      if (followMap) param['followConfig'] = followMap;
      
      mUp.httpUpMany(param,()=>{
        broadcast.send(broadcast.EXECUTE_UPDATE);
        navigator.back();
      });
    },
  }
}
</script>


<style src="@/_css/style.css"></style>
<style scoped>
.scroller {
  flex: 1;
}
.wrapper{
  padding-left: 40px;
  padding-right: 40px;
}
.line{
  height: 2px;
  margin-bottom: 40px;
}


.server {
  margin-top: 40px;
}

.api {
  margin: 40px;
}

.pair {
  margin-bottom: 40px;
}

.target {
  margin-bottom: 40px;
}

.param {
  margin-bottom: 40px;
}

.input {
  margin-bottom: 40px;
}

.set {
  margin-bottom: 40px;
}

.follow {
  margin-bottom: 40px;
}

/*************** 添加币对*/
.pair-but1 {
  align-items: center;
  justify-content: center;
  width: 248px;
  height: 96px;
  border-radius: 48px;
  border-width: 2px;

  margin-bottom: 40px;
}
.pair-but2 {
  align-items: center;
  justify-content: center;
  width: 232px;
  height: 84px;
  border-radius: 42px;
}
.pair-but3 {
  align-items: center;
  justify-content: center;
  width: 212px;
  height: 68px;
  border-radius: 34px;
}

/*************** 启动*/
.up{
  flex-direction: column;
  height: 164px;

  padding-left: 40px;
  padding-right: 40px;
}
.up-but{
  flex-direction: row;
  justify-content: center;
  align-items: center;
  height: 80px;
  border-radius: 4px;

  margin-top: 28px;
}
</style>